package logic

import (
	"context"
	"fmt"
	"wwdmc/models/mysql"
	"wwdmc/models/redis"
	"wwdmc/pkg"

	"wwdmc/wwdmcrpc/internal/svc"
	"wwdmc/wwdmcrpc/wwdmcrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *wwdmcrpc.LoginRequest) (*wwdmcrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var login mysql.Account
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&login)

	if login.ID == 0 {
		return nil, fmt.Errorf("未注册的用户不允许登录")
	}
	if login.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码不正确,登录失败")
	}
	get1 := redis.Client.Get("captcha" + in.Tel)
	if get1.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码未验证")
	}
	get2 := redis.Client.Get("sendsms" + in.Source + in.Tel)
	if get2.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信验证码未验证")
	}

	return &wwdmcrpc.LoginResponse{Id: int64(login.ID)}, nil
}
